from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View


class QQRedirect(View):
    def get(self,request):
        # 1、提取前端传参数next
        next = request.GET.get('next')

        # 2、使用QQLoginTool工具获取扫码页面链接
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            # 用户完成整个qq登陆流程之后，返回到美多到哪个页面
            state=next,  # http://www.meiduo.site:8080/
        )
        qq_login_url = oauth.get_qq_url()

        # 3、构建响应数据返回
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'login_url': qq_login_url
        })

class QQUserView(View):

    def get(self, request):

        code = request.GET.get('code')

        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            # 用户完成整个qq登陆流程之后，返回到美多到哪个页面
            state=next,  # http://www.meiduo.site:8080/
        )

        try:
            # 2、根据code获取AccessToken
            access_token = oauth.get_access_token(code)
            # 3、根据AccessToken获取openid
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'errmsg': '用户code无效！'
            })



        return JsonResponse({'code': 1, 'errmsg': 'ok'})

